package network;

import org.jgrapht.alg.util.Pair;

import java.util.ArrayList;

public class Ports {
    private int hash;
    public ArrayList<Port> ports;

    public Ports(ArrayList<Port> ports) {
        this.ports = (ArrayList<Port>) ports.clone();
        this.hash = this.getHash();
    }

    public Port get(int i) {
        return ports.get(i);
    }

    public void replace(int i, Port newPort) {
        this.hash ^= ports.get(i).hashCode();
        ports.set(i, newPort);
        this.hash ^= newPort.hashCode();
    }

    public void reverseArray(ArrayList<Pair<Port, Port>> changes) {
        for (Pair<Port, Port> entry : changes) {
            this.hash ^= entry.getFirst().hashCode() ^ entry.getSecond().hashCode();
            int i = entry.getSecond().getDevice().uid;
            assert ports.get(i) == entry.getFirst();
            ports.set(i, entry.getFirst());
        }
    }

    public Ports replaceArray(ArrayList<Pair<Port, Port>> changes) {
        for (Pair<Port, Port> entry : changes) {
            this.hash ^= entry.getFirst().hashCode() ^ entry.getSecond().hashCode();
            int i = entry.getFirst().getDevice().uid;
            assert ports.get(i) == entry.getFirst();
            ports.set(i, entry.getSecond());
        }
        return this;
    }

    private int getHash() {
        int hashCode = 0;
        for (Port e : this.ports)
            hashCode ^= ( e == null ? 0 : e.hashCode() );
        return hashCode;
    }

    @Override
    public int hashCode() {
        return this.hash;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Ports) {
            Ports t = (Ports) o;
            for (int i = 0; i < Device.cnt; i ++) {
                if (this.get(i) != t.get(i)) return false;
            }
            return true;
        }
        return false;
    }
}
